package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.util.JwtHelper;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.PatientMapper;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2023-06-01
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private PatientMapper patientMapper;

    @Autowired
    private PatientService patientService;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();

        if (StringUtils.isBlank(phone) || StringUtils.isBlank(code)) {
            throw new YyghException(20001, "手机号或验证码有误！");
        }

        //校验校验验证码
        String mobleCode =(String) redisTemplate.opsForValue().get(phone);
        if(!code.equals(mobleCode)) {
            throw new YyghException(20001,"验证码失败");
        }
        String openid = loginVo.getOpenid();
        UserInfo userInfo = new UserInfo();
        if (StringUtils.isEmpty(openid)) {
            //判断是否是首次登录
            QueryWrapper wrapper = new QueryWrapper<UserInfo>();
            wrapper.eq("phone", phone);
            userInfo = baseMapper.selectOne(wrapper);
            if (userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
        } else {
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("openid", openid);
            userInfo = baseMapper.selectOne(wrapper);
            QueryWrapper<UserInfo> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("phone", phone);
            UserInfo userInfo1 = baseMapper.selectOne(wrapper1);
            if (userInfo1 == null) {
                userInfo.setPhone(phone);
                baseMapper.updateById(userInfo);
            } else {
                //将微信对应的数据赋予手机号对应数据
                userInfo1.setOpenid(userInfo.getOpenid());
                userInfo1.setNickName(userInfo.getNickName());
                //保存手机号
                baseMapper.updateById(userInfo1);
                //删除微信对应的数据
                baseMapper.deleteById(userInfo.getId());
            }
        }


        if (userInfo.getStatus() == 0) {
            throw new YyghException(20001, "用户锁定中");
        }
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return map;
    }

    @Override
    public Page<UserInfo> getUserInfoPage(Integer pageNum, Integer limit, UserInfoQueryVo userInfoQueryVo) {
        Page<UserInfo> page = new Page<>(pageNum, limit);
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        String name = userInfoQueryVo.getKeyword();
        Integer status = userInfoQueryVo.getStatus();
        Integer authStatus = userInfoQueryVo.getAuthStatus(); //认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd(); //结束时间
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("name",name);
        }
        if(status != null) {
            wrapper.eq("status",status);
        }
        if(authStatus != null) {
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        Page<UserInfo> selectPage = baseMapper.selectPage(page, wrapper);
        selectPage.getRecords().stream().forEach(item->{
            this.packageUserInfo(item);
        });
        return selectPage;
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        if (status == 0 || status == 1) {
//            UserInfo userInfo = baseMapper.selectById(id);
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> detail(Long id) {
        UserInfo userInfo = baseMapper.selectById(id);
        QueryWrapper<Patient> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", id);
        List<Patient> patients = patientService.selectList(wrapper);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userInfo", userInfo);
        map.put("patients", patients);
        return map;
    }

    //编号变成对应值封装
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }
}
